# -*- utf-8 -*-
from apps.data_visual.models import TableNameAlias, FieldNameAlias
from apps.data_visual.serializers import TableNameAliasSerializer, FieldNameAliasSerializer
from apps.data_visual.sqla_models import get_tables, get_fields
from apps.data_visual.utils import field_alias_list
from utils.network import NeedLoginView, Result


class TbNameAliasView(NeedLoginView):
    def get(self, request):
        tb_names = get_tables().keys()

        table_name_alias = TableNameAlias.objects.filter(is_delete=False).order_by(
            'create_time')
        serializer = TableNameAliasSerializer(table_name_alias, many=True)
        ret = [{'column': i, 'alias': i} for i in tb_names]
        for item in serializer.data:
            for index, value in enumerate(ret):
                if item['table_name'] == value['column']:
                    ret[index]['alias'] = item['alias']

        return Result.success(data=ret)

    def post(self, request):
        data = request.data
        table_name = data['table_name']
        if table_name not in get_tables().keys():
            return Result.error(message=f"名为 {table_name} 的表不存在")
        alias = data['alias']
        TableNameAlias(table_name=table_name, alias=alias).save()
        return Result.success()

    def delete(self, request):
        data = request.data
        table_name = data['table_name']
        TableNameAlias.objects.filter(table_name=table_name).update(is_delete=True)
        return Result.success()


class FieldNameAliasView(NeedLoginView):
    def get(self, request):
        table_name = request.GET.get('table_name')
        ret = field_alias_list(table_name)
        return Result.success(data=ret)

    def post(self, request):
        FieldNameAlias(**request.data).save()
        return Result.success()

    def delete(self, request):
        data = request.data
        table_name = data['table_name']
        field_name = data['field_name']
        TableNameAlias.objects.filter(table_name=table_name, field_name=field_name).update(is_delete=True)
        return Result.success()


class ClearRepeatView(NeedLoginView):
    def get(self, request):
        return Result.error(message="Unknown error")
